package com.zhilianbao.leyaogo.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import com.bql.convenientlog.CLog;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.model.response.UserLoginInfo;
import com.zhilianbao.leyaogo.ui.activity.base.BaseOkHttpActivity;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.AwesomeEditTextView;
import com.zhilianbao.leyaogo.view.widgets.DelayButton;
import com.zlb.lxlibrary.service.LeXiuInitService;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import cn.zhilianbao.ice.service.IceService;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 注册页面
 * Created by gyt on 2016/11/17
 */
public class RegisterActivity extends BaseOkHttpActivity {

    @BindView(R.id.edt_login_userName)
    AwesomeEditTextView mEdtLoginUserName;
    @BindView(R.id.edt_login_verify_code)
    AwesomeEditTextView mEdtLoginVerifyCode;
    @BindView(R.id.btn_delay)
    DelayButton         mBtnDelay;
    @BindView(R.id.edt_login_password)
    AwesomeEditTextView mEdtLoginPassword;
    @BindView(R.id.tv_register)
    TextView            mTvRegister;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_register;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        initToolbar(getString(R.string.user_register));
        mEdtLoginUserName.addTextChangedListener(MyTextWatcher);
        mEdtLoginVerifyCode.addTextChangedListener(MyTextWatcher);
        mEdtLoginPassword.addTextChangedListener(MyTextWatcher);
        mTvRegister.setEnabled(false);
        mBtnDelay.setEnabledGo(false);

//        mEdtLoginUserName.setFocusable(true);
//        mEdtLoginUserName.setFocusableInTouchMode(true);
//        mEdtLoginUserName.requestFocus();
    }

    private void verifyMobilePhone() {
        final String phone = mEdtLoginUserName.getText().toString().trim();
        if (CheckUtils.isEmpty(phone)) {
            XToastUtils.showShortToast(getString(R.string.msg_login_input_mobile));
            return;
        }
        if (phone.length() != 11) {
            XToastUtils.showShortToast(R.string.wrong_phone_length);
            return;
        }

        if (!Utils.isPhoneNumber(phone)) {
            XToastUtils.showShortToast(R.string.wrong_phone_format);
            return;
        }

        if (!CheckUtils.isMobilePhone(phone)) {
            XToastUtils.showShortToast(R.string.invalid_phone_number);
            return;
        }


        AccountApi.verifyCellPhone(this, 0, phone, new JsonCallback<String>(this) {

            @Override
            public void onSuccess(String o, Call call, Response response) {
                CLog.d(o);
                if (o.equals(HttpConfig.MSG_CODE_412 + "")) {// 只有没有注册过的用户才会发送验证码
                    sendVerifyCode(phone);
                    mBtnDelay.setEnabled(false);
                } else if (o.equals(HttpConfig.MSG_CODE_413 + "")) {// 用户已注册，提示去登录
                    XToastUtils.showShortToast(getString(R.string.msg_registered_to_login));
                    Utils.putUserLoginName(phone);
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_BACK_TO_LOGIN_ACTIVITY));
//                    finish();
                }
            }

        });
    }


    /**
     * 发送验证码请求
     */
    private void sendVerifyCode(String mobile) {

        AccountApi.sendVerifyCode(this, mobile, new DialogCallback<Object>(this) {

            @Override
            public void onSuccess(Object o, Call call, Response response) {
                XToastUtils.showShortToast(getString(R.string.send_verify_code_suc));
                // 重新获取光标
//                mEdtLoginVerifyCode.requestFocus();
                mBtnDelay.startCountDown();
            }
        });
    }


    @OnClick({R.id.tv_register, R.id.btn_delay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_register:
                performRegister();
                break;
            case R.id.btn_delay:
                verifyMobilePhone();
                break;
        }
    }

    private void performRegister() {
        final String mobile = mEdtLoginUserName.getText().toString().trim();
        String code = mEdtLoginVerifyCode.getText().toString().trim();
        String pwd = mEdtLoginPassword.getText().toString().trim();


        AccountApi.regUser(RegisterActivity.this, mobile, pwd, code, new DialogCallback<String>(RegisterActivity.this, getResources().getString(R.string.hint_registering)) {

            @Override
            public void onSuccess(String code, Call call, Response response) {
                // 如果用户已经注册过
                if (code.equals(HttpConfig.MSG_CODE_413 + "")) {
                    XToastUtils.showShortToast(getString(R.string.msg_registered_to_login));
                    Utils.putUserLoginName(mobile);
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_BACK_TO_LOGIN_ACTIVITY));
//                    finish();
                } else {
                    Utils.putUserLoginName(mobile);
                    //                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_BACK_TO_LOGIN_ACTIVITY));
                    goLogin(mobile, pwd);
                    //                    finish();
                }
            }
        });
    }



    private void goLogin(String phoneNo, String password) {
        AccountApi.login(this, 0, phoneNo, password, new DialogCallback<UserLoginInfo>(this, getResources().getString(R.string.hint_register_sucs_to_login)) {

            @Override
            public void onSuccess(UserLoginInfo userLoginInfo, Call call, Response response) {

                //登录成功保存用户信息
                Utils.putUserLoginInfo(userLoginInfo);
                //登录成功初始化ICE
                IceService.getInstance().initIce();
                //
                LeXiuInitService.getInstance().onLegoLoginSuccess(userLoginInfo.getUserId() + "", userLoginInfo.getUserAlias(), Utils.returnUrlShow(userLoginInfo.getUserPic()), userLoginInfo.getTokenId(), Utils.getSupplierId() + "");
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_LOGIN_SUCCESS));
                //                    ThreadPool.postOnUiDelayed(() -> LogicCodeBlock.create().dispatchLogicCode(logicState), 500);
                finish();

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                finish();
            }
        });
    }


    private TextWatcher MyTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            enableSubmitBtn();
        }
    };

    private void enableSubmitBtn() {
        mTvRegister.setEnabled(mEdtLoginUserName.getText().length() != 0 && mEdtLoginVerifyCode.getText().length() != 0 && mEdtLoginPassword.getText().length() != 0);
        mBtnDelay.setEnabledGo(mEdtLoginUserName.getText().length() != 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MyTextWatcher != null) {
            mEdtLoginUserName.removeTextChangedListener(MyTextWatcher);
            mEdtLoginVerifyCode.removeTextChangedListener(MyTextWatcher);
            mEdtLoginPassword.removeTextChangedListener(MyTextWatcher);
            MyTextWatcher = null;
        }
    }


    @Override
    protected boolean isStatusDarkMode() {
        return true;
    }
}
